<?php
/**
 * Created by PhpStorm.
 * User: seven
 * Date: 2018/2/9
 * Time: 下午11:01
 *
 *
$res = FormatValidator::from("15044565444")
    ->isMobile(1, "需要邮箱")
    ->validate();
if($res){
    echo $res["message"];
}else{
    echo "验证通过";
}
 */
class FormatValidator {
    public $isDead = false;
    public $deadCode = -9879;
    public $deadMessage = "";

    public $src = "";

    private function isDead(){
        return $this->deadCode != -9879;
    }

    public static function from($src) {
        $f = new FormatValidator();
        $f->src = $src;
        return $f;
    }

    private static function checkRegMatch($src, $pattern){
        return preg_match( $pattern, $src );
    }

    public function isNotEmpty($code, $message){
        if($this->isDead()) return $this;
        if ( empty($this->src) ){
            $this->deadCode = $code;
            $this->deadMessage = $message;
        }
        return $this;
    }

    public function isEmail($code, $message){
        if($this->isDead()) return $this;
        $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
        if ( !preg_match( $pattern, $this->src ) ){
            $this->deadCode = $code;
            $this->deadMessage = $message;
        }
        return $this;
    }

    public function isMobile($code, $message){
        if($this->isDead()) return $this;
        $pattern = "/^1[34578]{1}\d{9}$/";
        if ( !preg_match( $pattern, $this->src ) ){
            $this->deadCode = $code;
            $this->deadMessage = $message;
        }
        return $this;
    }

    public function validate(){
        if($this->isDead()){
            $res = array();
            $res["code"] = $this->deadCode;
            $res["message"] = $this->deadMessage;
            return $res;
        }else{
            return null;
        }
    }
}
